# coding=utf-8

import datetime

from flask import render_template, url_for, redirect, current_app, sessions, request, flash, abort
from flask_login import login_required, login_user, logout_user, current_user, login_fresh

from config import BaseConfig
from . import blue_auth
from .forms import LoginForm, UserInfoUpdateForm
from ..models import User, Group, EngineRoom, Email
from .. import login_manager, db


@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))


@blue_auth.before_app_first_request
def init_data():
    from data import DEFAULT_GROUPS, DEFAULT_USERS, DEFAULT_ENGINEROOMS
    current_groups = Group.query.with_entities(Group.name).all()
    if len(current_groups) == 0:
        for g in DEFAULT_GROUPS.keys():
            new_group = Group()
            new_group.name = DEFAULT_GROUPS[g]['name']
            new_group.level = DEFAULT_GROUPS[g]['level']
            new_group.alias = DEFAULT_GROUPS[g]['alias']
            new_group.detail = DEFAULT_GROUPS[g]['detail']
            db.session.add(new_group)
        #
        db.session.commit()
    else:
        pass
    #
    current_users = User.query.with_entities(User.name).all()
    if len(current_users) == 0:
        for u in DEFAULT_USERS.keys():
            new_user = User()
            new_user.name = DEFAULT_USERS[u]['name']
            new_user.alias = DEFAULT_USERS[u]['alias']
            new_user.email = DEFAULT_USERS[u]['email']
            new_user.password = DEFAULT_USERS[u]['password']
            group_wanted = Group.query.filter_by(name=DEFAULT_USERS[u].get('group_name', 'UNKNOW')).first()
            if group_wanted:
                group_wanted.users.append(new_user)
            else:
                del new_user
                continue
            #
            db.session.add_all([new_user, group_wanted])
        #
    #
    current_enginerooms = EngineRoom.query.with_entities(EngineRoom.name).all()
    if len(current_enginerooms) == 0:
        for e in DEFAULT_ENGINEROOMS.keys():
            new_enginerooms = EngineRoom()
            new_enginerooms.id = DEFAULT_ENGINEROOMS[e]['id']
            new_enginerooms.name = DEFAULT_ENGINEROOMS[e]['name']
            new_enginerooms.alias = DEFAULT_ENGINEROOMS[e]['alias']
            db.session.add(new_enginerooms)
        #
        db.session.commit()
    else:
        pass

    current_email = Email.query.with_entities(Email.name).all()
    if len(current_email) == 0:
        if BaseConfig.MAIL_ADDRESSEE:
            addressee = BaseConfig.MAIL_ADDRESSEE
            email = Email(name='sanxian',alias=u'三线日报接收',address=addressee)
            db.session.add(email)
            db.session.commit()
        else:
            pass
    else:
        pass


@blue_auth.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('blue_duty.index'))
    #
    
    login_form = LoginForm()
    if login_form.validate_on_submit():
        user_name = login_form.uname.data.strip()
        user_pwd = login_form.pwd.data.strip()
        duser = User.query.filter_by(name=user_name).first()
        if duser:
            if duser.verify_password(user_pwd) and duser.status:
                login_user(duser)
                login_form.uname = ''
                login_form.pwd = ''
                return redirect(request.values.get('next') or url_for('blue_duty.index'))
            else:
                login_form.uname = ''
                login_form.pwd = ''
                if duser.status:
                    flash(u"账 户 或 密 码 错 误")
                    if request.values.get('next'):
                        return redirect(url_for('blue_auth.login', next=request.values.get('next')))
                    else:
                        return redirect(url_for('blue_auth.login'))
                    #
                else:
                    flash(u"账 户 被 禁 用")
                    return redirect(url_for('blue_auth.login'))
                #
            #
        else:
            flash(u"账 户 或 密 码 错 误")
            return redirect(url_for('blue_auth.login'))
        #
    else:
        login_form.uname.data = ''
        login_form.pwd.data = ''
    #
    
    url_next = request.values.get('next', '')
    return render_template('auth/login.html', form=login_form, url_next=url_next)


@blue_auth.route('/logout')
def logout():
    if current_user.is_authenticated:
        logout_user()
    #
    return redirect(url_for('blue_duty.index'))


@blue_auth.route('/user/info/<int:id>', methods=['GET', 'POST'])
@login_required
def user_info(id):
    if current_user.id == id:
        pass
    else:
        abort(403)
    
    template_params = {}
    user_info_form = UserInfoUpdateForm()

    this_user = User.query.filter_by(id=id).first()
    template_params['user_info_form'] = user_info_form
    template_params['user'] = this_user

    if user_info_form.validate_on_submit():
        user_new_alias = user_info_form.user_alias.data.strip()
        user_new_email = user_info_form.user_email.data.strip()
        user_new_isactive = user_info_form.user_isactive.data
        user_pwd_is_changed = user_info_form.pwd_is_changed.data
        user_old_pwd = user_info_form.old_pwd.data.strip()
        user_new_pwd01 = user_info_form.new_pwd01.data.strip()
        user_new_pwd02 = user_info_form.new_pwd02.data.strip()
        
        user_info_form.user_alias.data = ''
        user_info_form.user_email.data = ''
        user_info_form.user_isactive.data = ''
        user_info_form.pwd_is_changed.data = ''
        user_info_form.old_pwd.data = ''
        user_info_form.new_pwd01.data = ''
        user_info_form.new_pwd02.data = ''

        try:
            if user_pwd_is_changed:
                if user_old_pwd and user_new_pwd01 and user_new_pwd02:
                    if this_user.verify_password(user_old_pwd):
                        this_user.password = user_new_pwd01
                    else:
                        flash(u"旧 密 码 错 误", 'warning')
                        return redirect(url_for('blue_auth.user_info', id=this_user.id))
                else:
                    flash(u"新 / 旧 密 码 不 能 为 空", 'warning')
                    return redirect(url_for('blue_auth.user_info', id=this_user.id))
                #
            #
            this_user.alias = user_new_alias
            this_user.email = user_new_email
            this_user.status = user_new_isactive
            this_user.lastchange = datetime.datetime.now()

            db.session.add(this_user)
            db.session.commit()
        except Exception, e:
            flash(u"更 新 失 败", 'error')
            db.session.rollback()
            return redirect(url_for('blue_auth.user_info', id=this_user.id))
        else:
            flash(u"更 新 成 功", 'success')
        return redirect(url_for('blue_auth.user_info', id=this_user.id))
    else:
        pass
    #
    return render_template('auth/user_info.html', **template_params)